package cn.edu.sjtu.se.dslab.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sjtu.se.dslab.action.bean.PageBean;
import cn.edu.sjtu.se.dslab.auth.CommonVariableModel;
import cn.edu.sjtu.se.dslab.component.data.AvionicsEquipment;
import cn.edu.sjtu.se.dslab.component.data.DataAttribute;
import cn.edu.sjtu.se.dslab.component.data.DataComponent;
import cn.edu.sjtu.se.dslab.component.data.DataType;
import cn.edu.sjtu.se.dslab.component.data.DomainEntity;
import cn.edu.sjtu.se.dslab.component.data.EntityDiagram;
import cn.edu.sjtu.se.dslab.component.data.Operation;
import cn.edu.sjtu.se.dslab.component.data.util.DataComponentUtil;
import cn.edu.sjtu.se.dslab.component.data.util.DataTypeUtil;
import cn.edu.sjtu.se.dslab.component.data.util.DiagramXmlParser;
import cn.edu.sjtu.se.dslab.component.data.util.DomainEntityGenerator;
import cn.edu.sjtu.se.dslab.component.data.util.DomainEntityXMIGenerator;
import cn.edu.sjtu.se.dslab.component.method.InterfaceMethod;
import cn.edu.sjtu.se.dslab.service.IAvionicsEquipmentService;
import cn.edu.sjtu.se.dslab.service.IDataAttributeService;
import cn.edu.sjtu.se.dslab.service.IDataComponentService;
import cn.edu.sjtu.se.dslab.service.IDataTypeService;
import cn.edu.sjtu.se.dslab.service.IDiagramService;
import cn.edu.sjtu.se.dslab.service.IDomainEntityService;
import cn.edu.sjtu.se.dslab.service.IInterfaceMethodService;
import cn.edu.sjtu.se.dslab.service.IOperationService;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.FileUtil;
import cn.edu.sjtu.se.dslab.util.PackUtil;

@Controller
public class DomainEntityController {
	@Resource(name = "domainEntityService")
	IDomainEntityService domainEntityService;

	@Resource(name = "dataTypeService")
	IDataTypeService dataTypeService;

	@Resource(name = "dataAttributeService")
	IDataAttributeService dataAttributeService;

	@Resource(name = "interfaceMethodService")
	IInterfaceMethodService interfaceMethodService;

	@Resource(name = "operationService")
	IOperationService operationService;
	
	@Resource(name="diagramService")
	IDiagramService diagramService;
	
	@Resource(name="avionicsEquipmentService")
	IAvionicsEquipmentService avionicsEquipmentService;
	
	
	@Resource(name="dataComponentService")
	IDataComponentService dataComponentService;

	@Resource(name = "dataComponentUtil")
	DataComponentUtil dataComponentUtil;
	
	@Resource(name = "domainEntityXMIGenerator")
	DomainEntityXMIGenerator domainEntityXMIGenerator;
	
	@Resource(name = "domainEntityGenerator")
	DomainEntityGenerator domainEntityGenerator;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	private final static String DIAGRAM = "diagram";

	private final static String NAME = "name";

	private final static String TYPE = "type";

	private final static String CN_NAME = "cnName";

	private final static String URI = "uri";

	private final static String DESCRIPTION = "description";


	@RequestMapping(value = "/domain_entity/{type}/{uri}", method = RequestMethod.GET)
	public ModelAndView getDomainEntityByUri(
			@PathVariable(value = "type") String type,
			@PathVariable(value = "uri") String uri) {
		ModelAndView model = new ModelAndView();
		try {
			if (type.equals(Const.DATA_TYPE_URI)) {
				DataType dataType = dataTypeService
						.getDataTypeByUri(Const.URI_DATA_TYPE + ":" + uri);
				if (dataType != null) {
					model.setViewName("datatype_detail");
					model.addObject("item", dataType);
					DataTypeUtil dataTypeUtil = new DataTypeUtil();
					String code = dataTypeUtil.getDataTypeCode(dataType);
					// System.out.println("code"+code);
					model.addObject("code", code);
				}
				return model;
			} else if (type.equals(Const.AVIONICS_EQUIPMENT_URI)) {
				AvionicsEquipment equipment = avionicsEquipmentService.getAvionicsEquipmentByUri(Const.URI_AVIONICS_EQUIPMENT
								+":" + uri);
				if (equipment != null) {
					model.setViewName("equipment_detail");
					model.addObject("item", equipment);
				}
				return model;
			} else {
				DomainEntity entity = domainEntityService
						.getDomainEntityByUri(Const.URI_DOMAIN_ENTITY + ":"
								+ type + ":" + uri);
				if (entity != null) {
					model.setViewName("domain_entity_detail");
					model.addObject("item", entity);
				}
				return model;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}
	
	/**
	 * 下载该uri对应的文件所有文件，zip打包，以该DataEntity的名称命名 
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/{uri}/download",method = RequestMethod.GET)
	public void downloadDataEntityByUri(
			@PathVariable(value = "uri") String uri, HttpServletResponse response) throws FileNotFoundException,IOException{
			//将所有文件打包下载，包括继承项，组合项和依赖项
		DomainEntity entity = domainEntityService
				.getDomainEntityByUri(Const.URI_DOMAIN_ENTITY + ":"
						+ "data:" + uri);
			if (entity != null) {
				Map<Long , String> fileMap = dataComponentUtil.getDependence(entity);
				//包含所有的依赖文件的绝对路径
				List<String> filePaths = new ArrayList<String>(fileMap.values());
				//打包文件名称
				String zipName = entity.getName()+".zip";
				//打包文件保存路径-uri对应的文件夹下 
				String zipDir = Const.DOMAIN_ENTITY_GENERATE_PATH+entity.getUri().split(":")[entity.getUri().split(":").length -1];
				//获取绝对路径
				String realPath = Const.ABSOLUTE_GENERATE_PATH+zipDir;
				realPath = realPath.replace("\\", "/");
				for (int i = 0; i < filePaths.size(); i++) {
					filePaths.set(i, filePaths.get(i).replace("\\", "/"));
				}
//				System.out.println(filePaths.iterator().next());
//				System.out.println(realPath);
//				System.out.println(zipName);
				boolean result =PackUtil.zipList(filePaths,realPath , zipName);
				//server运行正确，成功打包
				if (result) {
					//System.out.print("result:"+result);
					File file = new File(realPath+"/"+zipName);
					InputStream is = new FileInputStream(file);
					// set content attributes for the response
					response.setContentType("application/octet-stream");
					response.setContentLength((int) file.length());
					// set headers for the response
			        String headerKey = "Content-Disposition";
			        String headerValue = String.format("attachment; filename=\"%s\"",
			        		zipName);
			        response.setHeader(headerKey, headerValue);
					IOUtils.copy(is, response.getOutputStream());
					response.flushBuffer();
				}else {
					String tips = "服务器错误，请稍后再试！";
					InputStream isInputStream = new ByteArrayInputStream(tips.getBytes("utf-8"));
					response.setContentType("text/plain");
					response.setContentLength(tips.getBytes("utf-8").length);
					IOUtils.copy(isInputStream, response.getOutputStream());
					response.flushBuffer();
				}
				
			}else {
				return;
			}
	}
	/**
	 * 下载该uri对应的数据实体的xmi文件，以该DataEntity的名称命名 
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/{uri}/download/xmi",method = RequestMethod.GET)
	public void downloadDataEntityXMIByUri(
			@PathVariable(value = "uri") String uri, HttpServletResponse response) throws FileNotFoundException,IOException{
			//将所有文件打包下载，包括继承项，组合项和依赖项
		DomainEntity entity = domainEntityService
				.getDomainEntityByUri(Const.URI_DOMAIN_ENTITY + ":"
						+ "data:" + uri);
			if (entity != null) {
				//文件名称
				String fileName = entity.getName()+".xmi";
				String filePath =Const.DOMAIN_ENTITY_GENERATE_PATH+
						entity.getUri().split(":")[entity.getUri().split(":").length -1] + "/"+fileName;
				String fileRealPath = FileUtil.getRootPath() + "generate/" + filePath;
				fileRealPath = fileRealPath.replace("\\", "/");
				File file = new File(fileRealPath);
				if (file.exists()) {
					file.delete();
					System.out.println("delete the xmi file!");
				}
				domainEntityXMIGenerator.generateEntity(entity, fileRealPath);
				file = getFile(fileRealPath);
				InputStream is = new FileInputStream(file);
				// set content attributes for the response
				response.setContentType("application/octet-stream");
				response.setContentLength((int) file.length());
				// set headers for the response
			    String headerKey = "Content-Disposition";
			    String headerValue = String.format("attachment; filename=\"%s\"",
			    		fileName);
			    response.setHeader(headerKey, headerValue);
				IOUtils.copy(is, response.getOutputStream());
				response.flushBuffer();
			}else {
				return;
			}
	}
	
	/**
	 * 下载该uri对应的文件，以该DataType的名称命名 
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/type/{uri}/download/xmi",method = RequestMethod.GET)
	public void downloadDataTypeXMIByUri(
			@PathVariable(value = "uri") String uri, HttpServletResponse response) throws FileNotFoundException,IOException{
			//将所有文件打包下载，包括继承项，组合项和依赖项
		DataType dataType = dataTypeService
				.getDataTypeByUri(Const.URI_DATA_TYPE + ":" + uri);
			if (dataType != null && !dataType.getCategory().equals(Const.DATA_TYPE_BASIC)) {
				String filename = dataType.getName()
						.replace(" ", "_").toLowerCase()+ ".xmi";
				String zipDir = Const.DOMAIN_ENTITY_GENERATE_PATH+dataType.getUri().split(":")[dataType.getUri().split(":").length -1];
				String realPath = FileUtil.getRootPath() + "generate/" + zipDir;
				realPath = realPath.replace("\\", "/");
				realPath = realPath+"/"+filename;
				File file = getFile(realPath);
				if (file.exists()) {
					file.delete();
					System.out.println("delete the xmi file!");
				}
				domainEntityXMIGenerator.generateEntity(dataType, realPath);
				file = getFile(realPath);
				InputStream is = new FileInputStream(file);
				// set content attributes for the response
				response.setContentType("application/octet-stream");
				response.setContentLength((int) file.length());
				// set headers for the response
				String headerKey = "Content-Disposition";
				String headerValue = String.format("attachment; filename=\"%s\"",
						filename);
				response.setHeader(headerKey, headerValue);
				IOUtils.copy(is, response.getOutputStream());
				response.flushBuffer();
				
			}else {
				return;
			}
	}
	
	/**
	 * 下载该uri对应的xmi文件，以该DataType的名称命名
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/type/{uri}/download",method = RequestMethod.GET)
	public void downloadDataTypeByUri(
			@PathVariable(value = "uri") String uri, HttpServletResponse response) throws FileNotFoundException,IOException{
			//将所有文件打包下载，包括继承项，组合项和依赖项
		DataType dataType = dataTypeService
				.getDataTypeByUri(Const.URI_DATA_TYPE + ":" + uri);
			if (dataType != null && !dataType.getCategory().equals(Const.DATA_TYPE_BASIC)) {
				String filename = dataType.getName()
						.replace(" ", "_").toLowerCase()+ ".h";
				String zipDir = Const.DOMAIN_ENTITY_GENERATE_PATH+dataType.getUri().split(":")[dataType.getUri().split(":").length -1];
				String realPath = Const.ABSOLUTE_GENERATE_PATH+zipDir;
				realPath = realPath.replace("\\", "/");
				realPath = realPath+"/"+filename;
				System.out.println(realPath);
				File file = getFile(realPath);
				if (file.exists()) {
					file.delete();
					System.out.println("delete the xmi file!");
				}
				domainEntityGenerator.generateDataType(dataType, realPath);
				file = getFile(realPath);
				InputStream is = new FileInputStream(file);
				// set content attributes for the response
				response.setContentType("application/octet-stream");
				response.setContentLength((int) file.length());
				// set headers for the response
				String headerKey = "Content-Disposition";
				String headerValue = String.format("attachment; filename=\"%s\"",
						filename);
				response.setHeader(headerKey, headerValue);
				IOUtils.copy(is, response.getOutputStream());
				response.flushBuffer();
				
			}else {
				return;
			}
	}
	protected File getFile(String targetFileName) throws IOException{
		File targetFile = new File(targetFileName);
		System.out.println(targetFileName);
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		if (!targetFile.exists()){
			targetFile.createNewFile();
		}
		return targetFile;
	}
	@RequestMapping(value = "/domain_entity/{type}/{uri}/delete", method = RequestMethod.GET)
	public String deleteEntityByUri(
			@PathVariable(value = "type") String type,
			@PathVariable(value = "uri") String uri) throws IOException{
		try {
			if (type.equals(Const.DATA_TYPE_URI)) {
				DataType dataType = dataTypeService
						.getDataTypeByUri(Const.URI_DATA_TYPE + ":" + uri);
				if (dataType != null) {
					dataType.setDeleted(true);
					dataTypeService.updateDataType(dataType);
				}
			} else if (type.equals(Const.AVIONICS_EQUIPMENT_URI)) {
				AvionicsEquipment equipment = avionicsEquipmentService.getAvionicsEquipmentByUri(Const.URI_AVIONICS_EQUIPMENT
								+":" + uri);
				equipment.setDeleted(true);
				avionicsEquipmentService.updateAvionicsEquipment(equipment);
			} else {
				DomainEntity entity = domainEntityService
						.getDomainEntityByUri(Const.URI_DOMAIN_ENTITY + ":"
								+ type + ":" + uri);
				entity.setDeleted(true);
				domainEntityService.updateDomainEntity(entity);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "redirect:/domain_entity";
	}
	
	@RequestMapping(value = "/domain_entity", method = RequestMethod.GET)
	public ModelAndView getDomainEntityList(
			@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
			@CookieValue(value = "domain_type", defaultValue = "all") String domainType) {
		ModelAndView model = new ModelAndView();
		model.setViewName("domain_entity");
		try {
			if (domainType.equals("all")) {
				PageBean<DomainEntity> bean = domainEntityService
						.getPageBean(pageNum);
				model.addObject("bean", bean);
			}else if (domainType.equals("equipment")) {
				PageBean<AvionicsEquipment> bean = avionicsEquipmentService
						.getAvionicsEquipmentByPageNum(pageNum);
				model.addObject("bean", bean);
			}else if (domainType.equals("type")) {
				PageBean<DataType> bean = dataTypeService.getPageBean(pageNum);
				model.addObject("bean", bean);
			}else if (domainType.equals("data")) {
				PageBean<DomainEntity> bean = domainEntityService
						.getDataEntityPageBean(pageNum);
				model.addObject("bean", bean);
			}
			return model;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}
	
	@RequestMapping(value = "/domain_entity/data", method = RequestMethod.GET)
	public ModelAndView getDataEntityList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
			@CookieValue(value = "domain_type", defaultValue = "data") String domainType,HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		model.setViewName("domain_entity");
		try {
			Cookie foo = new Cookie("domain_type", "data"); //bake cookie	
			response.addCookie(foo); //put cookie in response 
			PageBean<DomainEntity> bean = domainEntityService
					.getDataEntityPageBean(pageNum);
			model.addObject("bean", bean);
			return model;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}

	@RequestMapping(value = "/json/{uri}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getDomainEntityJsonByUri(
			@PathVariable(value = "uri") String uri) {
		Map<String, Object> modelMap = new HashMap<String, Object>(3);
		modelMap.put("total", "1");
		try {
			DomainEntity damainEntity = domainEntityService
					.getDomainEntityByUri(uri);
			if (damainEntity != null) {
				damainEntity.setChildList(null);
				modelMap.put("data", damainEntity);
				modelMap.put("success", "true");
			} else {
				modelMap.put("success", "false");
			}
			return modelMap;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			modelMap.put("success", "false");
		}
		return modelMap;
	}

	/**
	 * 添加数据实体的get方法controller
	 * 
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/add", method = RequestMethod.GET)
	public ModelAndView addDataEntity() {
		ModelAndView model = new ModelAndView();
		model.setViewName("add_data_entity");
		try {
			List<DataType> _typeList = dataTypeService.getDataTypeList();
			List<DomainEntity> typeList = domainEntityService.getAllDomainEntity();
			typeList.addAll(_typeList);
			model.addObject("typeList", typeList);
			return model;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}

	/**
	 * 绘制数据实体类图的get方法controller
	 * 
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/{uri}/diagram", method = RequestMethod.GET)
	public ModelAndView drawDataEntityClassDiagram(
			@PathVariable(value = "uri") String uri) {
		ModelAndView model = new ModelAndView();
		model.setViewName("edit_diagram");
		try {
			DomainEntity entity = domainEntityService
					.getDomainEntityByUri(Const.URI_DATA_ENTITY + ":" + uri);
			DiagramXmlParser parser = new DiagramXmlParser();
			String diagram = parser.parseDataEntity2Diagram(entity);
			model.addObject(DIAGRAM, diagram);
			model.addObject("uri",uri);
			return model;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}

	/**
	 * 绘制数据实体类图的post方法controller
	 * 
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/{uri}/diagram", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> drawDataEntityClassDiagram(
			@PathVariable(value = "uri") String uri,@RequestParam(value="uris[]", required=false) String[] uris,
			@RequestParam(value="currentdiagram", required=true) String currentdiagram) {
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		if(uris != null){
			//添加新添加的关联项
			Set<DomainEntity>  domainEntities = new HashSet<DomainEntity>();
			for (int i = 0; i < uris.length; i++) {
				DomainEntity newEntity = domainEntityService.getDomainEntityByUri(uris[i]);
				domainEntities.add(newEntity);
				System.out.println("newEntity:"+newEntity.getName());
			}
			DiagramXmlParser parser = new DiagramXmlParser();
			String data = parser.addNewConnection(currentdiagram, domainEntities);
			modelMap.put("data",data);
			modelMap.put("success", "true");
			return modelMap;
		}
		modelMap.put("success", "false");
		return modelMap;
		
	}
	
	
	/**
	 * 提交数据实体类图的post方法controller
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/{uri}/diagram/submit", method = RequestMethod.POST)
	public String submitDataEntityClassDiagram(
			@PathVariable(value = "uri") String uri,
			@RequestParam(value="currentdiagram", required=true) String currentdiagram) {
		DomainEntity entity = domainEntityService
				.getDomainEntityByUri(Const.URI_DATA_ENTITY + ":" + uri);
		// 确定diagram可以正常保存
		EntityDiagram diagram = new EntityDiagram();
		diagramService.addDiagram(diagram);
		String file = diagram.getUri().split(":")[diagram.getUri().split(":").length - 1] + "/diagram.xml";
		String realPath = Const.ABSOLUTE_DIAGRAM_PATH + file;
		System.out.println("realPath:" + realPath);
		try {
			FileWriter fWriter = null;
			File writeFile = getFile(realPath);
			fWriter = new FileWriter(writeFile);
			fWriter.write(currentdiagram);
			fWriter.flush();
			fWriter.close();
			diagram.setFilepath(file);
			diagramService.updateDiagram(diagram);                					
		
		//String file = entity.getUri().split(":")[entity.getUri().split(":").length - 1] + "/diagram.xml";
		//String realPath = Const.ABSOLUTE_DIAGRAM_PATH + file;
		//System.out.println("realPath:" + realPath);
		//File file2 = new File(realPath);
		//if (file2.exists()) {
		//	file2.delete();
		//	System.out.println("delete the diagram file!");
		//}
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
			diagram = null;
		}
		DiagramXmlParser parser = new DiagramXmlParser();
		parser.createDiagram(entity, domainEntityService, diagram,currentdiagram);
		return "redirect:/" + entity.getUri().replace(":", "/");
	}
	
	/**
	 * 添加数据实体的post方法controller
	 * 
	 * @return
	 */
	@RequestMapping(value = "/domain_entity/data/add", method = RequestMethod.POST)
	public String addDataEntity(DomainEntity entity,
			@RequestParam(required = false) String[] attrs,
			@RequestParam(required = false) long[] types,
			@RequestParam(required = false) long[] re_type,
			@RequestParam(required = false) String[] f_name,
			@RequestParam(required = false) String[] f_params,
			@RequestParam(required = false ) String[] f_sig,
			@RequestParam(required = false) String[] f_impl,
			@RequestParam(required = false) String[] f_params_id,
			@RequestParam(required = false) String[] f_description,
			@RequestParam(value="version",required = false) String version) {
		logger.info("添加 DataEntity:" + new Date().toString() + "----start");
		entity.setType(Const.DATA_ENTITY);
		domainEntityService.addDomainEntity(entity);
		/**
		 * 处理属性列表
		 */
		Set<DataAttribute> attributes = new HashSet<DataAttribute>();
		if (types != null && attrs != null && types.length == attrs.length) {
			for (int i = 0; i < types.length; i++) {
				DataAttribute attribute = new DataAttribute();
				attribute.setEntity(entity);
				attribute.setName(attrs[i]);
				attribute.setLength(0);
				attribute.setOrder(i + 1);
				DomainEntity type = domainEntityService.getDomainEntityById(types[i]);
				attribute.setType(type);
				dataAttributeService.addDataAttribute(attribute);
				attributes.add(attribute);
			}
		}
		entity.setAttributes(attributes);
		/**
		 * 处理方法
		 */
		Set<Operation> operations = new HashSet<Operation>();
		if (re_type != null && f_name != null && f_params != null
				&& f_description != null && re_type.length == f_name.length) {
			for (int i = 0; i < re_type.length; i++) {
				InterfaceMethod method = new InterfaceMethod();
				StringBuffer paramBuffer = new StringBuffer();
				if (f_params.length != 0){
				String[] params = f_params[i].split(";");
				if (params!= null && params.length>0) {	
					paramBuffer.append(params[0]);
					for (int j = 1; j < params.length; j++) {
						paramBuffer.append(","+params[j].trim());
					}
				}
				}
				method.setArguments(paramBuffer.toString());
				/**
				 * 当函数只有一个时，对于带有逗号的字段，springmvc会自动转为字符串，需要手动将其重新拼接
				 */
				if (f_name.length == 1) {
					StringBuilder sb = new StringBuilder(f_description.length);
					int offset = f_description.length - 1;
					for( int des = 0; des < offset; des++ )
					{
					    sb.append(f_description[des]).append(",");
					}
					sb.append(f_description[offset]);
					method.setDescription(sb.toString());
					
					StringBuilder sbs = new StringBuilder(f_sig.length);
					int offsets = f_sig.length - 1;
					for( int sig = 0; sig < offsets; sig++ )
					{
						sbs.append(f_sig[sig]).append(",");
					}
					sbs.append(f_sig[offsets]);
					method.setMethodSigniture(sbs.toString());
					
					StringBuilder sbImpl = new StringBuilder(f_impl.length);
					int offsetImpl = f_impl.length - 1;
					for( int impl = 0; impl < offsetImpl; impl++ )
					{
						sbImpl.append(f_impl[impl]).append(",");
					}
					sbImpl.append(f_impl[offsetImpl]);
					method.setImplementation(sbImpl.toString());
				}else {
					method.setDescription(f_description[i].trim());
					method.setMethodSigniture(f_sig[i]);
					method.setImplementation(f_impl[i]);
				}
				
				method.setDepType(f_params_id[i].trim());
				//method.setImplementation(f_impl[i]);
				//method.setDescription(f_description[i]);
				method.setName(f_name[i]);
				DomainEntity type = domainEntityService.getDomainEntityById(re_type[i]);
				method.setReturnType(type);
				//method.setMethodSigniture(f_sig[i]);
				interfaceMethodService.addInterfaceMethod(method);
				Operation operation = new Operation();
				operation.setEntity(entity);
				operation.setInterfaceMethod(method);
				operationService.addOperation(operation);
				operations.add(operation);
			}
		}
		entity.setOpertions(operations);
		/**
		 * 自动添加对应的data component(需要改动)
		 */
		DataComponent component = new DataComponent();
		component.setCreateTime(new Date());
		component.setLastModified(new Date());
		component.setType(Const.COMPONENT_TYPE_DATA);
		
		Subject user = SecurityUtils.getSubject();
		if (user!= null) {
			CommonVariableModel model = (CommonVariableModel) user.getPrincipals()
					.getPrimaryPrincipal();
			component.setOwner(model.getUser());
		}else {
			System.out.println("no user is logined");
		}
		
		component.setEntity(entity);
		component.setName(entity.getName());
		component.setDescription(entity.getDescription());
		component.setVersion(version);
		String filePath = dataComponentUtil.generateDomainEntityFile(entity);
		component.setFilepath(filePath);
		
		dataComponentService.addDataComponent(component);
		logger.info("添加DataEntity:" + new Date().toString() + "----end");
		return "redirect:/" + entity.getUri().replace(":", "/");
	}

	@RequestMapping(value = "/domain_entity/json/list", method = RequestMethod.GET,produces="application/json")
	@ResponseBody
	public Map<String, Object> getDataEntityListToJson() {

		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		try {
			List<DomainEntity> list = domainEntityService.getAllDomainEntity();
			List<Map<String, String>> data = new ArrayList<Map<String, String>>();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, String> map = new HashMap<String, String>();
					map.put(URI, list.get(i).getUri());
					map.put(NAME, list.get(i).getName());
					map.put(TYPE, list.get(i).getType());
					map.put(CN_NAME, list.get(i).getCnName());
					map.put(DESCRIPTION, list.get(i).getDescription());
					data.add(map);
				}
			}
			modelMap.put("data", data);
			modelMap.put("success", "true");
			return modelMap;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			modelMap.put("success", "false");
		}
		return modelMap;
	}

}
